package gridfs.util;

import gridfs.fuse.GridFS;
import org.bson.Document;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledUtil {
    public static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    public static final Map<String, LinkedList<Document>> cache = new ConcurrentHashMap<>();
    public static void start() {
        // 注意此处线程个数为1
        executorService.scheduleAtFixedRate(()->{
            Iterator<Map.Entry<Long, List<GridFS.TokenBucket>>> it = GridFS.pidToBucketList.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<Long, List<GridFS.TokenBucket>> item = it.next();
                ProcessHandle.of(item.getKey()).ifPresent(p->{
                    if (!p.isAlive())
                        it.remove();
                });
            }
            cache.clear();
            // 延迟0s执行，周期为10s
        }, 0, 10, TimeUnit.SECONDS);
    }
}
